package nccloud.web.pp.priceaudit.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import nc.itf.uap.pf.IPfExchangeService;
import nc.pubitf.pu.m20.pu.m28.IQuery20For28;
import nc.ui.querytemplate.querytree.IQueryScheme;
import nc.vo.pp.m28.entity.PriceAuditVO;
import nc.vo.pp.util.AggVOHelper;
import nc.vo.pu.m20.entity.PraybillHeaderVO;
import nc.vo.pu.m20.entity.PraybillItemVO;
import nc.vo.pu.m20.entity.PraybillVO;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pub.lang.UFDateTime;
import nc.vo.pubapp.pattern.pub.SqlBuilder;
import nc.vo.pubapp.query2.sql.process.QuerySchemeProcessor;
import nc.vo.scmpub.res.billtype.POBillType;
import nc.vo.scmpub.res.billtype.PPBillType;
import nc.vo.scmpub.util.TransferSortUtil;
import nccloud.dto.baseapp.querytree.dataformat.Condition;
import nccloud.dto.baseapp.querytree.dataformat.QueryCondition;
import nccloud.dto.baseapp.querytree.dataformat.QueryTreeFormatVO;
import nccloud.dto.baseapp.querytree.dataformat.Value;
import nccloud.dto.purp.price.entity.BaseVariable;
import nccloud.dto.purp.price.entity.PkTsParamsVO;
import nccloud.dto.purp.price.entity.TransferData;
import nccloud.dto.purp.price.entity.TransferInfo;
import nccloud.dto.scmpub.pub.utils.SCMRowNoUtils;
import nccloud.framework.core.env.Locator;
import nccloud.framework.core.exception.ExceptionUtils;
import nccloud.framework.core.json.IJson;
import nccloud.framework.service.ServiceLocator;
import nccloud.framework.web.action.itf.ICommonAction;
import nccloud.framework.web.container.IRequest;
import nccloud.framework.web.json.JsonFactory;
import nccloud.framework.web.ui.config.ITempletResource;
import nccloud.framework.web.ui.config.Item;
import nccloud.framework.web.ui.config.PageTemplet;
import nccloud.framework.web.ui.config.TempletQueryPara;
import nccloud.framework.web.ui.pattern.billcard.BillCard;
import nccloud.framework.web.ui.pattern.billcard.BillCardOperator;
import nccloud.pubitf.platform.query.INCCloudQueryService;
import nccloud.pubitf.purp.priceaudit.service.ITransferDoAfterService;
import nccloud.web.pp.priceaudit.util.PriceAuditScaleUtil;











public class Transfer20Action
  implements ICommonAction
{
  public Object doAction(IRequest request) {
    BillCard[] cards = null;
    try {
      String read = request.read();
      IJson json = JsonFactory.create();
      
      TransferInfo info = (TransferInfo)json.fromJson(read, TransferInfo.class);
      
      Map<String, UFDateTime> idTsMap = new HashMap<String, UFDateTime>();
      
      Map<String, UFDateTime> idTsMapBody = new HashMap<String, UFDateTime>();
      TransferData[] datas = info.getData();
      Set<String> bodyPks = new HashSet<String>();
      if (datas != null) {
        for (TransferData data : datas) {
          PkTsParamsVO head = data.getHead();
          if (head != null) {
            idTsMap.put(head.getPk(), new UFDateTime(head.getTs()));
          }
          PkTsParamsVO[] bodys = data.getBodys();
          if (bodys != null) {
            for (PkTsParamsVO body : bodys) {
              idTsMap.put(body.getPk(), new UFDateTime(body.getTs()));
              idTsMapBody.put(body.getPk(), new UFDateTime(body.getTs()));
              bodyPks.add(body.getPk());
            } 
          }
        } 
      }
      
      IQueryScheme scheme = getQueryScheme(info, bodyPks);
      IQuery20For28 service = (IQuery20For28)ServiceLocator.find(IQuery20For28.class);

      
      PraybillVO[] sorceVOs = service.queryPrayBills(scheme);

      
      if (sorceVOs != null) {
        for (PraybillVO vo : sorceVOs) {
          PraybillHeaderVO head = vo.getHVO();
          head.setTs((UFDateTime)idTsMap.get(head.getPk_praybill()));
          
          PraybillItemVO[] items = vo.getBVO();
          if (items != null) {
            for (PraybillItemVO item : items) {
              if (idTsMap.get(item.getPk_praybill_b()) != null) {
                item.setTs((UFDateTime)idTsMap.get(item.getPk_praybill_b()));
              }
            } 
          }
        } 
      }
      
      IPfExchangeService service1 = (IPfExchangeService)ServiceLocator.find(IPfExchangeService.class);
      PriceAuditVO[] vos = (PriceAuditVO[])service1.runChangeDataAry(POBillType.PrayBill
          .getCode(), PPBillType.PriceAudit.getCode(), sorceVOs, null);

      
      ITempletResource resourc = (ITempletResource)Locator.find(ITempletResource.class);
      TempletQueryPara para = new TempletQueryPara();
      para.setPagecode(info.getPagecode());
      para.setTemplateid(info.getTempletId());
      PageTemplet ptemplet = resourc.query(para);
      UFBoolean bqueryhisprice = UFBoolean.valueOf(false);
      Item hispriceItem = ptemplet.getArea("card_head").getItemByCode("bqueryhisprice");
      if (hispriceItem != null && hispriceItem.getInitialvalue() != null) {
        bqueryhisprice = UFBoolean.valueOf(String.valueOf(hispriceItem.getInitialvalue().getValue()));
      }
      ITransferDoAfterService doAfterservice = (ITransferDoAfterService)ServiceLocator.find(ITransferDoAfterService.class);
      vos = doAfterservice.doAfterFor20(vos, sorceVOs, bqueryhisprice);
      vos = (PriceAuditVO[])(new TransferSortUtil("vsrcrowno", "vsrccode")).sort(vos);
      BillCardOperator operator = new BillCardOperator(info.getTempletId(), info.getPagecode());
      if (vos != null && vos.length > 0) {
        cards = new BillCard[vos.length];
        for (int i = 0; i < vos.length; i++) {
          int[] rows = getItemRows(vos[i]);
          SCMRowNoUtils.setMultiSelectRowNo(vos[i].getChildrenVO(), rows);
          BillCard billCard = operator.toCard(vos[i]);
          afterProcess(billCard);
          cards[i] = billCard;
        } 
      } 
    } catch (Exception e) {
      ExceptionUtils.wrapException(e);
    } 
    
    return cards;
  }





  
  public void afterProcess(BillCard card) {
    PriceAuditScaleUtil buyUtil = new PriceAuditScaleUtil();
    buyUtil.processBillCard(card);
  }







  
  private IQueryScheme getQueryScheme(TransferInfo queryInfo, Set<String> bodyPks) {
    BaseVariable bv = new BaseVariable();
    QueryTreeFormatVO qtf = new QueryTreeFormatVO();
    qtf.setQuerytype(bv.getTree());
    qtf.setOid(queryInfo.getOid());
    qtf.setPageInfo(null);
    qtf.setQueryAreaCode(queryInfo.getQueryAreaCode());
    qtf.setPageCode(queryInfo.getPagecode());
    QueryCondition querycondition = new QueryCondition();
    List<Condition> conditions = new ArrayList<Condition>();
    Condition condition = new Condition();
    condition.setOprtype(bv.getEqual());
    condition.setField(bv.getPk_praybill_bb());
    StringBuilder sb = new StringBuilder();
    for (String pk : bodyPks) {
      sb.append(pk).append(bv.getComma());
    }
    if (sb.length() > 0) {
      sb.deleteCharAt(sb.length() - 1);
    }
    Value value = new Value();
    value.setFirstvalue(sb.toString());
    condition.setValue(value);
    condition.setLogic("and");
    conditions.add(condition);
    querycondition.setConditions(conditions);
    querycondition.setLogic("and");
    qtf.setQuerycondition(querycondition);
    
    INCCloudQueryService queryutil = (INCCloudQueryService)ServiceLocator.find(INCCloudQueryService.class);
    IQueryScheme queryScheme = queryutil.convertCondition(qtf);
    QuerySchemeProcessor processor = new QuerySchemeProcessor(queryScheme);
    
    String table = processor.getTableAliasOfAttribute("pk_praybill_b.pk_praybill_b");
    
    SqlBuilder sqlb = new SqlBuilder();
    sqlb.append(" and ");
    sqlb.append(table + ".pk_praybill_b", (String[])bodyPks
        .toArray(new String[bodyPks.size()]));
    
    processor.appendWhere(sqlb.toString());




    
    return queryScheme;
  }
  private int[] getItemRows(PriceAuditVO aggVO) {
    AggVOHelper<PriceAuditVO> helper = new AggVOHelper<PriceAuditVO>(aggVO);
    int[] trows = new int[aggVO.getChildrenVO().length];
    List<Integer> lists = new ArrayList<Integer>();
    for (int i = 0; i < trows.length; i++) {
      Object object = helper.getBodyValue(i, "pk_material");
      if (object != null) {
        lists.add(Integer.valueOf(i));
      }
    } 
    int[] rows = new int[lists.size()];
    for (int n = 0; n < lists.size(); n++) {
      rows[n] = ((Integer)lists.get(n)).intValue();
    }
    return rows;
  }
}
